<script context="module">
  export async function preload(page, session) {
    if (!session.user) {
      this.error(403, "对不起，请登录之后再查看本页面！");
      return;
    }
    let { p } = page.query;
    if (!p) {
      p = 1;
    }
    p = parseInt(p);
    const response = await Promise.all([
      this.fetch("/api2/productcategories"),
    ]);
    const categories = await response[0].json();
    return { categories:categories.categories };
  }
</script>

<script>
  import { goto, stores } from "@sapper/app";
  import dayjs from "dayjs";
  import relativeTime from "dayjs/plugin/relativeTime";
  import "dayjs/locale/zh-cn";
  import { toast } from "@zerodevx/svelte-toast";
  import {
    Modal,
    ModalBody,
    ModalFooter,
    ModalHeader
  } from 'sveltestrap/src';
  let open = false;
  const toggle = () => (open = !open);
  dayjs.extend(relativeTime);
  dayjs.locale("zh-cn");
  const { preloading, page, session } = stores();
  let path;
  let selectCategory;
  $: path = $page.path;
  export let categories;
  let per_page = 24;
  async function deleteCategory(id) {
    const response = await fetch("/api2/productcategories?id=" + id, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("删除成功，有10分钟缓存，请稍候再查看列表！");
    }
  }
  function openEdit(category) {
    selectCategory= category;
    open = !open;
  }
  async function save() {
    const response = await fetch("/api2/productcategories", {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        title: selectCategory.title,
        id: selectCategory._id
      }),
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("编辑成功，因为缓存，可能几分钟之后才能看见修改结果！");
      open=!open;
    }
  }
</script>

<svelte:head>
  <title>商品物品分类 - 记账中心</title>
</svelte:head>
<div class="content">
  <div class="row">
  </div>
  <div class="row mt-4">
    <table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">分类名</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody>
        {#each categories as category}
          <tr>
            <td>{category.title}</td>
            <td>
              <div class="btn-group" role="group">
                <button class="btn btn-primary" on:click="{()=>{openEdit(category)}}">编辑</button>
                <button class="btn btn-danger" on:click="{()=>{deleteCategory(category._id)}}">删除</button>
              </div>
            </td>
          </tr>
        {/each}
      </tbody>
    </table>
  </div>
  <Modal isOpen={open} {toggle}>
    <ModalHeader {toggle}>编辑分类</ModalHeader>
    <ModalBody>
      <input
        type="text"
        id="title"
        class="form-control"
        placeholder="分类名称"
        bind:value={selectCategory.title}
      />
    </ModalBody>
    <ModalFooter>
      <button class="btn btn-primary" on:click="{save}">保存</button>
      <button class="btn btn-danger" on:click="{()=>{open=!open}}">关闭</button>
    </ModalFooter>
  </Modal>
</div>
